package com.example.capsule_chat0322.fragment;

import static android.content.Context.WIFI_SERVICE;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentResultListener;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.capsule_chat0322.R;
import com.example.capsule_chat0322.activity.AddSecretRoomActivity;
import com.example.capsule_chat0322.activity.ChatActivity;
import com.example.capsule_chat0322.adapter.ChatRoomListAdapter;
import com.example.capsule_chat0322.bean.RoomBean;
import com.example.capsule_chat0322.connect.PositionOperation;
import com.example.capsule_chat0322.connect.ServerOperation;
import com.example.capsule_chat0322.global.GlobalAssistMap;
import com.example.capsule_chat0322.interfaces.ChatRoomItemOnClickInterface;
import com.example.capsule_chat0322.request.RoomRequest;
import com.example.capsule_chat0322.utils.AlterUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author zhuzhiming
 * @Date 2022/5/1 14:11
 */
public class ChatRoomListFragment extends Fragment {

    private List<RoomBean> roomList;
    private RecyclerView chatRoomRecyclerView;
    private ChatRoomListAdapter chatRoomListAdapter;
    private TextView chat_room_list_update;
    private ImageView add_secret_room;
    private String macAddress;
    private static boolean isFirst = true;
    private static boolean isFirstUploadPosition = true;
    private int prePosition = 0;
    private volatile String isConnect;
    private Map<String, String> macAddressMap = new HashMap<>();
    private int count = 0;
    private final static int ADD_SECRET_ROOM = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getParentFragmentManager().setFragmentResultListener("skipToChatRoomListMark", this, new FragmentResultListener() {
            @Override
            public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle bundle) {
                String result = bundle.getString("isSkip");
                if (result != null) {
                    isFirst = false;
                }
            }
        });

        Bundle result = new Bundle();
        result.putString("isSkip", "true");
        getParentFragmentManager().setFragmentResult("skipToChatRoomListMark", result);

    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.chat_room_list, null);
        initView(view);//初始化UI控件
        return view;
    }


    public void initView(View view) {

        macAddress = getMacAddress();
        if (macAddress == null) {
            AlterUtils.alertByDialog(getActivity(),
                    "错误", "请打开Wifi~",
                    "我知道了", null,
                    "狠心离开", null);
        }

        chatRoomRecyclerView = view.findViewById(R.id.chat_room_recycler_view);
        chat_room_list_update = view.findViewById(R.id.chat_room_list_update);
        add_secret_room = view.findViewById(R.id.add_secret_room);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        chatRoomRecyclerView.setLayoutManager(layoutManager);

        isConnect = System.getProperty("isConnect");
        if (isConnect == null || "false".equals(isConnect)) {
            try {
                Thread.sleep(300);
                isConnect = System.getProperty("isConnect");
                if (isConnect == null || "false".equals(isConnect)) {

                    DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            // initView(view);
                        }
                    };

                    DialogInterface.OnClickListener neutralListener = new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            System.exit(0);
                        }
                    };
                    AlterUtils.alertByDialog(getActivity(), "提醒", "连接服务器失败~~", "再次尝试连接", positiveListener, "狠心离开", neutralListener);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        Handler handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message message) {
                List<RoomBean> rooms = (List<RoomBean>) message.obj;
                roomList = rooms;
                chatRoomListAdapter = new ChatRoomListAdapter(rooms);
                chatRoomRecyclerView.setAdapter(chatRoomListAdapter);
                adapterAddListener(chatRoomListAdapter);
                chatRoomListAdapter.notifyItemInserted(rooms.size() > 0 ? rooms.size() - 1 : 0);
                chatRoomRecyclerView.scrollToPosition(0);
                if (isFirstUploadPosition) {
                    isFirstUploadPosition = false;
                    PositionOperation.getLocation(getContext(), null);
                }
                return true;
            }
        });

        if (isFirst && macAddress != null) {
            doGetRoomList(getActivity(), handler, macAddress, true);
        }
        chatRoomRecyclerView.setAdapter(chatRoomListAdapter);
        if (roomList != null) {
            chatRoomListAdapter.notifyItemInserted(roomList.size() > 0 ? roomList.size() - 1 : 0);
            chatRoomRecyclerView.scrollToPosition(prePosition);
        }

        chat_room_list_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (macAddress == null) {
                    macAddress = getMacAddress();
                    if (macAddress != null) {
                        doGetRoomList(getActivity(), handler, macAddress, false);
                        chatRoomListAdapter = new ChatRoomListAdapter(roomList);
                        chatRoomRecyclerView.setAdapter(chatRoomListAdapter);
                        adapterAddListener(chatRoomListAdapter);
                        chatRoomListAdapter.notifyItemInserted(roomList.size() > 0 ? roomList.size() - 1 : 0);
                        chatRoomRecyclerView.scrollToPosition(0);
                    }
                    return;
                }

                doGetRoomList(getActivity(), handler, macAddress, false);

            }
        });

        add_secret_room.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(getContext(), AddSecretRoomActivity.class);
                startActivityForResult(intent, ADD_SECRET_ROOM);
            }
        });

    }


    public String getMacAddress() {

        if (macAddressMap.get("macAddress") != null) {
            return macAddressMap.get("macAddress");
        }

        if (ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(requireActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        } else {
            WifiManager wifiManage = (WifiManager) requireActivity().getApplicationContext().getSystemService(WIFI_SERVICE);
            WifiInfo wifiinfo = wifiManage.getConnectionInfo();
            macAddress = wifiinfo.getBSSID();//获取当前连接网络的mac地址;
        }
        if (macAddress == null) {
            return null;
        }
        macAddress = "34:29:12:50:C6:04";
        macAddressMap.put("macAddress", macAddress);
        return macAddress;
        // return macAddress;
    }


    private void doGetRoomList(Context context, Handler handler, String macAddress, boolean auto) {

        isConnect = System.getProperty("isConnect");
        if (isConnect == null || "false".equals(isConnect)) {
            return;
        }
        String userId = (String) GlobalAssistMap.getObject("userId");
        if (userId == null) {
            try {
                Thread.sleep(200);
                userId = (String) GlobalAssistMap.getObject("userId");
                if (userId == null) {
                    Thread.sleep(300);
                    userId = (String) GlobalAssistMap.getObject("userId");
                    if (userId == null) {
                        Thread.sleep(500);
                        userId = (String) GlobalAssistMap.getObject("userId");
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if (userId == null) {
            return;
        }

        roomList = RoomRequest.getRoomList(context, handler, userId, macAddress, auto);
        chatRoomListAdapter = new ChatRoomListAdapter(roomList);
        adapterAddListener(chatRoomListAdapter);
        if (roomList != null && roomList.size() > 0) {
            prePosition = roomList.size() - 1;
        }

    }


    public void adapterAddListener(ChatRoomListAdapter chatRoomListAdapter) {

        if (chatRoomListAdapter == null) {
            return;
        }

        chatRoomListAdapter.setChatRoomItemClickListener(new ChatRoomItemOnClickInterface() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position, String roomName) {

                ServerOperation.connectChatRoom(roomName);
                Intent intent = new Intent();
                intent.setClass(getContext(), ChatActivity.class);
                intent.putExtra("roomName", roomName);
                startActivity(intent);

            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isFirst = true;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == ADD_SECRET_ROOM) {
            String roomName = (String) GlobalAssistMap.getObject("secretRoomName");
            GlobalAssistMap.removeObject("secretRoomName");
            RoomBean roomBean = new RoomBean();
            roomBean.setRoomName(roomName);
            roomList.add(0, roomBean);
            chatRoomListAdapter = new ChatRoomListAdapter(roomList);
            chatRoomRecyclerView.setAdapter(chatRoomListAdapter);
            adapterAddListener(chatRoomListAdapter);
            chatRoomListAdapter.notifyItemInserted(roomList.size() > 0 ? roomList.size() - 1 : 0);
            chatRoomRecyclerView.scrollToPosition(0);

        }

    }
}
